package com.my.chapter18;

import net.mindview.util.TextFile;
import nu.xom.*;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.util.*;

public class practice32 {
    static String path = ".\\src\\com\\my\\chapter18\\";
    static Element getXML(Map.Entry<String,Integer> me) {
        Element record = new Element("record");
        Element word = new Element("word");
        word.appendChild(me.getKey());
        Element freq = new Element("frequency");
        freq.appendChild(me.getValue().toString());
        record.appendChild(word);
        record.appendChild(freq);
        return record;
    }

    public static void main(String[] args) throws Exception {
        Map<String,Integer> wordsStat =
                new HashMap<String,Integer>();
        for(String word :
                new TextFile(path + "practice32.java", "\\W+")) {
            Integer freq = wordsStat.get(word);
            wordsStat.put(word, freq == null ? 1 : freq + 1);
        }
        Element root = new Element("words");
        for(Map.Entry<String,Integer> me : wordsStat.entrySet())
            root.appendChild(getXML(me));
        Document doc = new Document(root);
        Person.format(System.out, doc);
        Person.format(
                new BufferedOutputStream(new FileOutputStream(
                        path + "WordsInfo.xml")), doc);
    }
}
